package br.com.maps.contacts.database;

import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.database.SQLException;
import br.com.maps.contacts.Contact;
import br.com.maps.fragments.ContacDataListener;

public class DataBaseFetcher {

	private ProgressDialog progressDialog;
	private Context context;
	private DBHandler db;
	private DBVersionHandler dbVersionHandler;

	public DataBaseFetcher(Context context, DBVersionHandler dbVersionHandler) {
		this.context = context;
		this.dbVersionHandler = dbVersionHandler;
	}

	public void execute(List<Contact>... params) {
		List<Contact> contacts = params[0];
		int dbVersion = this.dbVersionHandler.getDBVersion();
		int newDBVersion = dbVersion + 1;
		boolean result;
		try {
			this.onPreExecute();
			this.db = new DBHandler(this.context, newDBVersion);
			for (Contact contact : contacts) {
				this.db.save(contact);
			}
			this.dbVersionHandler.saveNewVersion(newDBVersion);
		} catch (SQLException e) {
			result = false;
		} finally {
			this.db.close();
		}
		result = true;
		this.onPostExecute(result);
	}

	protected void onPreExecute() {
		this.progressDialog = new ProgressDialog(this.context);
		this.progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		this.progressDialog.setMessage("Updating database...");
		this.progressDialog.show();
	}

	protected void onPostExecute(Boolean result) {
		try {
			if (result) {
				this.progressDialog.setMessage("Success!");
			} else {
				this.progressDialog.setMessage("Error Updating DB!");
			}
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
		}
		this.progressDialog.dismiss();
		ContacDataListener mra = (ContacDataListener) this.context;
		mra.dataSetChanged();
	}

}
